//=========|==================================================================
// #region | 导入外部库
//
let gulp = require('gulp');
let ts = require('gulp-typescript');
let exec = require('child_process').exec;
let spawn = require('child_process').spawn;
var del = require('del');
let open = require('gulp-open');
let sourcemaps = require('gulp-sourcemaps');
let mocha = require('gulp-mocha');
var env = require('gulp-env');
var git = require('gulp-git');
//
// #endregion
//=========|==================================================================

//=========|==================================================================
// #region | 单项任务
//

//目录常量
const PATHS = {
    scripts:['./src/**/*.ts'],
    output:'./build',
};

gulp.task('clean', function(cb) {
    del([PATHS.output]);
    cb();
});
  
//编译ts文件
gulp.task('build-ts', function(cb){
    let tsp = ts.createProject('tsconfig.json'); //使用tsconfig.json文件配置tsc
    gulp.src(PATHS.scripts)
    .pipe(sourcemaps.init()) // This means sourcemaps will be generated
    .pipe(tsp(ts.reporter.defaultReporter()))
    .pipe(sourcemaps.write()) // Now the sourcemaps are added to the .js file
    .pipe(gulp.dest(PATHS.output));   
    cb();
});

gulp.task('build', function(){
    return spawn('tsc', [], { stdio: 'inherit'})
});

gulp.task('set-dev-node-env', function() {
    return process.env.NODE_ENV = 'development';
});

gulp.task('set-prod-node-env', function(cb) {
    process.env.NODE_ENV = 'production';
    return cb();
});

let child;
//自动重启服务器
gulp.task('supervisor', function(){
    const envs = env.set({
        NODE_ENV: 'debug'
      });

    return spawn('supervisor', 
      ['-w', 'build/', './build/app/app.js'], 
      {stdio: 'inherit'});
    // child = exec('supervisor -w build/ ./build/app/app.js',(error,stdout,stderr)=>{
    //     console.log(`stdout: ${stdout}`);
    //     console.log(`stderr: ${stderr}`);
    //     if (error !== null) {
    //         console.log(`exec error: ${error}`);
    //     }
    // });
});

gulp.task('start', gulp.series('set-dev-node-env', 'build', 'supervisor'));

gulp.task('deploy', function(){
    // git push
});


gulp.task('gitpull', function(cb){
    git.pull('origin', ['master'], function (err) {
      if (err) throw err;
    });
    cb();
});

gulp.task('npminstall', function(){
        return spawn('npm',  ['install'], { stdio: 'inherit'})
    }
);

gulp.task('nodedebug', function(){
    process.env.NODE_ENV = 'production';
    return spawn('node',  
                ['--inspect=0.0.0.0:9229', './build/app/app.js'], 
                { stdio: 'inherit'});
});

gulp.task('pmstart', function(){
    return spawn('sudo pm2', 
                ['start', 'build/app.js', '--name=wzlzPaymentCallbackServer'], 
                {stdio: 'inherit'});
})


gulp.task('pmdel', function(){
    return spawn('pm2', 
                ['delete', 'wzlzPaymentCallbackServer'], 
                {stdio: 'inherit'});
})

gulp.task('pmrestart', gulp.series('pmdel', 'pmstart'));
//
// #endregion
//=========|==================================================================

//=========|==================================================================
// #region | 服务器端的指令
//
/**
 * gulp debug 命令: 启动远程调试
 */
gulp.task('debug', gulp.series('gitpull', // 拉去代码
                                'npminstall',  // npm 安装更新的包
                                'clean',  // 清理 build文件夹
                                'build',  // 重新编译
                                'set-prod-node-env', // 设置环境变量
                                'nodedebug') // 启动 Node dbug
); 


gulp.task('pm', gulp.series('gitpull', // 拉去代码
            'npminstall',  // npm 安装更新的包
            'clean',  // 清理 build文件夹
            'build',  // 重新编译
            'set-prod-node-env', // 设置环境变量
            'pmstart') //
);
//
// #endregion
//=========|==================================================================

//=========|==================================================================
// #region | Mocha
//
gulp.task('mocha', () => {
    let path = './src/test/local/**/*.ts';
    if (process.argv.length >= 5 && process.argv[4] == "--file"){
        path = process.argv[5];
    }
    return gulp.src([path], {read: false})
                .pipe(mocha({require: 'ts-node/register', reporter: 'spec', exit: true}))
});

gulp.task('mocharemote', () =>
    gulp.src(['./src/test/remote/**/*.ts'], {read: false})
        // `gulp-mocha` needs filepaths so you can't have any plugins before it
        .pipe(mocha({require: 'ts-node/register', reporter: 'spec', exit: true, timeout: 10000}))
    // return spawn('mocha', 
    //             ['--colors', '-r', 'ts-node/register', './src/test/remote/**/*.ts'], 
    //             {stdio: 'inherit'});
    // }
);
//
// #endregion
//=========|==================================================================
